<?php
/**
 * 匠言知识付费
 * Author: 山西匠言网络科技有限公司
 * This is not a free software, it under the license terms, you can visit https://www.zsffzxkc.cn/ get more details.
 */
namespace app\index\controller;
use app\index\controller\Base;
use think\Db;
use Payment\Wechat;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
require_once EXTEND_PATH.'Payment/example/phpqrcode/phpqrcode.php';
class Pay extends  Base
{
    //微信支付回调
    public function wechat_notify(){
        $testxml  = file_get_contents("php://input");  //接收微信发送的支付成功信息
        $result = $this->xmlToArray($testxml);
        $data1=array(
            'is_pay'=>1,
            'paytime'=>time(),
            'paydetail'=>json_encode($result)
        );
        if($result['trade_type'] == 'JSAPI' || $result['trade_type'] == 'APP' || $result['trade_type'] == 'NATIVE'){
            if($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS'){
                $orderdetail = Db::name('mediaorder')
                    ->where('orderid',$result['out_trade_no'])
                    ->find();
                if($orderdetail['is_pay']==0){
                    $res=Db::name('mediaorder')
                        ->where('orderid',$result['out_trade_no'])
                        ->update($data1);
                    if($res){
                        $this->check_order($result['out_trade_no']);
                        $this->paysuccessmsg($result['out_trade_no']);
                        $this->Yjset($result['out_trade_no']);
                        $this->Jsmoney($result['out_trade_no']);
                        $this->othermoney($result['out_trade_no']);
                    }
                }
                echo 'SUCCESS';
            }
            else{
                echo "fail";
            }
        }
    }
    // 分配资源下载、问答等其他收益
    private function othermoney($orderid) {
        $orderinfo=db('mediaorder')->where(['orderid' => $orderid])->find();
        $goodstype=$orderinfo['goodstype'];
        if($goodstype=='filesdownload' || $goodstype=='wenda'){
            $uniacid=1;
            $vipinfo=Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->find();
            $userid=$orderinfo['uid'];
            $setting=$this->get_set(strtoupper($goodstype));
            // 新的佣金消息
            $msg = array(
                'first' => array(
                    'value' => "恭喜，您获得了一笔新的收益",
                    'color' => '#ff510'
                ),
                'keyword1' => array(
                    'value' => '',
                    'color' => '#ff510'
                ),
                'keyword2' => array(
                    'value' => $orderinfo['price'].'元',
                    'color' => '#ff510'
                ),
                'keyword3' => array(
                    'value' => date('Y-m-d H:i:s',time()),
                    'color' => '#ff510'
                ),
                'remark' => array(
                    'value' => "感谢你的使用，再接再厉哦！",
                    'color' => '#ff510'
                ),
            );
            $jsmoney=sprintf("%.3f", $orderinfo['price']*$setting['yj']);
            if($goodstype=='filesdownload'){
                $goodsinfo=db('ziyuan')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                if($goodsinfo['uid'] == ''){
                    return false;
                }else{
                    $tuserinfo = db('user')->where(['acid'=>$uniacid,'id'=>$goodsinfo['uid']])->find();
                    $tres=db('user')->where(['acid'=>$uniacid,'id'=>$goodsinfo['uid']])->setInc('yongjin',$jsmoney);
                }
            }elseif($goodstype=='wenda'){
                $goodsinfo=db('user')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                if(!empty($goodsinfo)){
                    $tuserinfo = $goodsinfo;
                    $tres=db('user')->where(['acid'=>$uniacid,'id'=>$goodsinfo['id']])->setInc('yongjin',$jsmoney);
                }
            }
            if($tres){
                $msg['first']['value']='恭喜您有新的收益啦';
                $msg['keyword1']['value']=$jsmoney.'元';
                $msg['remark']['value']='收益来自'.$vipinfo['nickname'].'的贡献，请再接再厉哦！';
                if($tuserinfo['gzh_openid']){
                    $this->sendTpl($tuserinfo['gzh_openid'],$setting['msg_newyj'],$msg);
                }
                $data=array(
                    'acid'=>$uniacid,
                    'orderid'=>$orderid,
                    'goodstype'=>$orderinfo['goodstype'],
                    'source_uid'=>$userid,
                    'shouyi_uid'=>$tuserinfo['id'],
                    'event'=>$goodstype.'收益',
                    'yongjin'=>$jsmoney,
                    'createtime'=>time()
                );
                db('yjmingxi')->insert($data);
            }
        }
    }
    // 分配讲师收益
    private function Jsmoney($orderid) {
        $orderinfo=db('mediaorder')->where(['orderid' => $orderid])->find();
        $goodstype=$orderinfo['goodstype'];
        if($goodstype=='course' || $goodstype=='live'){
        $uniacid=1;
        $vipinfo=Db::name('user')
            ->where('id',$orderinfo['uid'])
            ->find();
        $userid=$orderinfo['uid'];
        $setting=$this->get_set('BASE');
        // 新的佣金消息
        $msg = array(
            'first' => array(
                'value' => "恭喜，您获得了一笔新的分销佣金",
                'color' => '#ff510'
            ),
            'keyword1' => array(
                'value' => '',
                'color' => '#ff510'
            ),
            'keyword2' => array(
                'value' => $orderinfo['price'].'元',
                'color' => '#ff510'
            ),
            'keyword3' => array(
                'value' => date('Y-m-d H:i:s',time()),
                'color' => '#ff510'
            ),
            'remark' => array(
                'value' => "感谢你的使用，再接再厉哦！",
                'color' => '#ff510'
            ),
        );


            if($goodstype=='course'){
                if($orderinfo['sonid']==0){
                    $goodsinfo=db('coursemenu')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                }else{
                    $menuinfo=db('coursemenu')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                    $goodsinfo=db('course')->where(['acid'=>$uniacid,'menuid'=>$orderinfo['menuid'],'id'=>$orderinfo['sonid']])->find();
                    $goodsinfo['tid']=$menuinfo['tid'];
                }
            }elseif($goodstype=='live'){
                $goodsinfo=db('zhibo')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
            }
            //讲师收益分配
            $tinfo=db('teacher')->where(['acid'=>$uniacid,'id'=>$goodsinfo['tid']])->find();
            if($tinfo['jsyj'] != 0){
                $setting['jsyj'] = $tinfo['jsyj'];
            }
            $tuserinfo=db('user')->where(['acid'=>$uniacid,'id'=>$tinfo['uid']])->find();
            $jsmoney=sprintf("%.3f", $orderinfo['price']*$setting['jsyj']);
            $tres=db('user')->where(['acid'=>$uniacid,'id'=>$tinfo['uid']])->setInc('yongjin',$jsmoney);
            if($tres){
                $msg['first']['value']='恭喜您的课程有新的收益啦';
                $msg['keyword1']['value']=$jsmoney.'元';
                $msg['remark']['value']='课程销售收益来自'.$vipinfo['nickname'].'的贡献，请再接再厉哦！';
                if($tuserinfo['gzh_openid']){
                    $this->sendTpl($tuserinfo['gzh_openid'],$setting['msg_newyj'],$msg);
                }
                $data=array(
                    'acid'=>$uniacid,
                    'orderid'=>$orderid,
                    'goodstype'=>$orderinfo['goodstype'],
                    'source_uid'=>$userid,
                    'shouyi_uid'=>$tinfo['uid'],
                    'event'=>'课程销售收益',
                    'yongjin'=>$jsmoney,
                    'createtime'=>time()
                );
                db('yjmingxi')->insert($data);
            }
        }
    }
    // 分配分销佣金
    private function Yjset($orderid) {
        //二级分销 佣金分配请购买商业版
    }
    private function paysuccessmsg($orderid){
        $uniacid=1;
        $orderinfo=Db::name('mediaorder')
            ->where('orderid',$orderid)
            ->find();
        $goodstype=$orderinfo['goodstype'];
        if($goodstype=='course'){
            if($orderinfo['sonid']==0){
                $goodsinfo=db('coursemenu')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                $goodsinfo['name']=$goodsinfo['menuname'];
            }else{
                $menuinfo=db('coursemenu')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
                $goodsinfo=db('course')->where(['acid'=>$uniacid,'menuid'=>$orderinfo['menuid'],'id'=>$orderinfo['sonid']])->find();
                $goodsinfo['name']=$goodsinfo['coursename'];
            }
        }elseif($goodstype=='live'){
            $goodsinfo=db('zhibo')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
            $goodsinfo['name']=$goodsinfo['zbtitle'];
        }elseif($goodstype=='exam'){
            $goodsinfo=db('exam')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
        }elseif($goodstype=='perform'){
            $goodsinfo=db('resources')->where(['acid'=>$uniacid,'id'=>$orderinfo['resources_id']])->find();
        }
        elseif($goodstype=='mall'){
            $goodsinfo=db('goods')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
        }elseif($goodstype=='pxcourse'){
            $goodsinfo=db('pxcourse')->where(['acid'=>$uniacid,'id'=>$orderinfo['menuid']])->find();
        }elseif($goodstype=='vip'){
            $newids=explode(",",$orderinfo['menuid']);
            $viptimeid=$newids[1];
            $viplevelid=$newids[0];
            $db1=db('viptime');
            $db2=db('viplevel');
            $viptimeinfo=$db1->where(['acid'=>$uniacid])->where('id',$viptimeid)->find();
            $viplevelinfo=$db2->where(['acid'=>$uniacid])->where('id',$viplevelid)->find();
            $goodsinfo['name']=$viplevelinfo['name'].'-'.$viptimeinfo['name'];
        }elseif($goodstype=='filesdownload'){
            $goodsinfo['name']='资源下载';
        }elseif($goodstype=='wenda'){
            $goodsinfo['name']='付费问答';
        }
        $userdata=Db::name('user')
            ->where('id',$orderinfo['uid'])
            ->find();
        $set=$this->get_set('BASE');
        // 购买成功消息
        $msg = array(
            'first' => array(
                'value' => "您的订单支付成功",
                'color' => '#ff510'
            ),
            'keyword1' => array(
                'value' => $orderid,
                'color' => '#ff510'
            ),
            'keyword2' => array(
                'value' => $goodsinfo['name'],
                'color' => '#ff510'
            ),
            'keyword3' => array(
                'value' => date('Y-m-d H:i:s',time()),
                'color' => '#ff510'
            ),
            'remark' => array(
                'value' => "支付金额：￥".$orderinfo['price'],
                'color' => '#ff510'
            ),
        );
        if($userdata['gzh_openid']!=''){
            $this->sendTpl($userdata['gzh_openid'],$set['msg_kcbuyok'],$msg);
        }
    }
    //充值、会员升级、商品赠积分、减库存加销量、兑换+支付方式的积分商品给用户减积分
    public function check_order($orderid){
        $map=array(
            'acid'=>1
        );
        $orderinfo=Db::name('mediaorder')
            ->where('orderid',$orderid)
            ->find();
        $userinfo=Db::name('user')
            ->where('id',$orderinfo['uid'])
            ->find();
        // 给用户减积分
        if($orderinfo['order_type']=='credit'){
            Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->setDec('credit',$orderinfo['credit']);
        }
        if($orderinfo['goodstype']=='chongzhi'){
            Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->setInc('money',$orderinfo['price']);
        }elseif($orderinfo['goodstype']=='vip'){
            $newids=explode(",",$orderinfo['menuid']);
            $viptimeid=$newids[1];
            $viplevelid=$newids[0];
            $data1=array(
                'is_vip'=>1,
                'vip_state'=>'正常',
                'viptypeid'=>$viptimeid,
                'viplevelid'=>$viplevelid,
                'vipsj_orderid'=>$orderid,
                'vipsj_fangshi'=>'usersj'
            );
            Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->update($data1);
        }elseif($orderinfo['goodstype']=='course'){
            $coursemenu=Db::name('coursemenu')
                ->where('id',$orderinfo['menuid'])
                ->find();
            Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->setInc('credit',$coursemenu['zsscore']);
        }elseif($orderinfo['goodstype']=='mall'){
            $coursemenu=Db::name('goods')
                ->where('id',$orderinfo['menuid'])
                ->find();
            if($coursemenu['stock']!=0){
                db('goods')->where('id',$orderinfo['menuid'])->setField('stock',$coursemenu['stock']-$orderinfo['num']);
            }
            db('goods')->where('id',$orderinfo['menuid'])->setField('sales',$coursemenu['sales']+$orderinfo['num']);
            Db::name('user')
                ->where('id',$orderinfo['uid'])
                ->setInc('credit',$coursemenu['zsscore']);
        }
    }
    public function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //支付宝支付异步回调
    public function alipay_notify(){
        $parameters=input('post.');
        if($parameters['trade_status'] == 'TRADE_FINISHED' || $parameters['trade_status'] == 'TRADE_SUCCESS') {
            $data1=array(
                'is_pay'=>1,
                'paytime'=>time(),
                'paydetail'=>json_encode($parameters)
            );
            $orderdetail = Db::name('mediaorder')
                ->where('orderid',$parameters['out_trade_no'])
                ->find();
            if($orderdetail['is_pay']==0) {
                $res = Db::name('mediaorder')
                    ->where('orderid', $parameters['out_trade_no'])
                    ->update($data1);
                if ($res) {
                    $this->check_order($parameters['out_trade_no']);
                    $this->paysuccessmsg($parameters['out_trade_no']);
                    $this->Yjset($parameters['out_trade_no']);
                    $this->Jsmoney($parameters['out_trade_no']);
                }
            }
            echo "success";
        }else{
            echo "fail";
        }
    }
    //支付宝H5同步回调
    public function alipay_return(){
        $set=$this->get_set('H5');
        $returnUrl = $set['url'];
        header('Location:'.$returnUrl);
    }
    //支付宝PC版同步回调
    public function alipay_pc_return(){
        $set=$this->get_set('PC');
        $returnUrl = $set['url'];
        header('Location:'.$returnUrl);
    }
    private function getOptions()
    {
        $set=db('set_alipay')->where(['acid'=>1])->find();
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $set['appid'];
        $options->merchantPrivateKey = $set['privatekey'];
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
//        $options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
//        $options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
//        $options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        $options->alipayPublicKey =$set['publickey'];
        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = 'https://'.$_SERVER['HTTP_HOST'].'/index.php/index/pay/alipay_notify';

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        //$options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";
        return $options;

    }
    public function order_make(){
        if(!request()->isPost()){
            $this->result(1,'请求方式有误','',0,'json');
        }
        $orderid = date("YmdHis",time()). rand('10000000','99999999');
        $input=input('post.');
        if($input['goodstype']=='course'){
            $menuinfo=Db::name('coursemenu')
                ->where(['acid'=>1,'id'=>$input['menuid']])
                ->find();
            if(isset($input['yxqid'])){
                if($input['yxqid']!=0){
                    $yxqdata=db('course_yxq')->where(['acid'=>1,'id'=>$input['yxqid']])->find();
                    $input['endtime'] = time() + 86400 * $yxqdata['days'];
                }
            }
        }
        if($input['price']==0 && $input['pay_type']=='yhm'){
            $data = array(
                'orderid'=>$orderid,
                'ordertime'=>time(),
                'acid'=>1,
                'is_pay'=>1,
                'paytime'=>time()
            );
            $data1=array_merge($input,$data);
            $res=Db::name('mediaorder')
                ->insert($data1);
            if($res){
                db('yhm')->where(['num'=>$input['yhm'],'acid'=>1])->update(['uid'=>$input['uid'],'hexiaotime'=>time(),'is_jh'=>1]);
                $this->result(0,'优惠码支付成功','',0,'json');
            }
        }else{
            $data = array(
                'orderid'=>$orderid,
                'ordertime'=>time(),
                'acid'=>1,
                'is_pay'=>0,
            );
            $apptype=isset($input['apptype'])?$input['apptype']:'';
            $data1=array_merge($input,$data);
            $res=Db::name('mediaorder')
                ->insert($data1);

            if($res){
                $map=array(
                    'acid'=>1
                );
                if($input['pay_type']=='wxpay'){
                    if($apptype=='MP-WEIXIN' || $apptype=='H5') {
                        //公众号h5和微信小程序支付
                        $data2 = array(
                            'nonce_str' => md5(rand(100000, 999999)),//随机串
                            'sign_type' => 'MD5',
                            'body' => '商品购买',//商品描述
                            'out_trade_no' => $orderid,//订单号
                            'total_fee' => $input['price'] * 100,//总金额(金额计数单位为：分)
                            'spbill_create_ip' => '127.0.0.1',//终端ip
                            'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/index.php/index/pay/wechat_notify',
                            'trade_type' => 'JSAPI',//下订单类型
                            'openid' => $input['openid']//微信openID
                        );
                        if ($apptype == 'MP-WEIXIN') {
                            $db = Db::name('set_smallapp');

                        } elseif ($apptype == 'H5') {
                            $db = Db::name('set_h5');
                        }
                        $set = $db->where($map)->find();
                        $data2['appid'] = $set['appid'];
                        $data2['mch_id'] = $set['mchid'];
                        $wechat = new Wechat($set['appid'], $set['mchid'], $set['paysecret'], $set['appsecret']);
                        $jsApiPayData = $wechat->jsApiOrder($data2);
                        echo json_encode($jsApiPayData);
                    }elseif ($apptype=='PC'){
                        //PC版微信扫码支付请购买商业版
                    }elseif ($apptype=='APP-PLUS'){
                        //APP版微信支付请购买商业版
                    }elseif ($apptype=='NORMAL-H5'){
                        //H5版(非微信浏览器)微信支付请购买商业版
                    }elseif ($apptype=='MP-TOUTIAO'){
                        //头条抖音小程序微信支付请购买商业版
                    }

                }elseif($input['pay_type']=='alipay'){
                    Factory::setOptions($this->getOptions());
                    if ($apptype=='H5') {
                        //支付宝H5支付
                        $set=$this->get_set('H5');
                        $quitUrl = $set['url'];
                        $result = Factory::payment()->wap()->pay("订单支付", $orderid, $input['price'], $quitUrl, 'https://' . $_SERVER['HTTP_HOST'] . '/index.php/index/pay/alipay_return');
                        echo json_encode($result);
                    }elseif ($apptype=='APP-PLUS'){
                        //支付宝APP支付
                    }elseif ($apptype=='PC'){
                        //支付宝PC扫码支付
                    }elseif ($apptype=='MP-TOUTIAO'){
                        //支付宝头条抖音小程序支付
                    }
                }elseif ($input['pay_type']=='credit'){
                    //积分支付
                    $userinfo=db('user')->where(['acid'=>1,'id'=>$input['uid']])->find();
                    if($userinfo['credit']>$input['credit']){
                        $res2=db('mediaorder')->where(['acid'=>1,'orderid'=>$orderid])->update(['is_pay'=>1,'paytime'=>time()]);
                        if($res2){
                            $this->check_order($orderid);
                            $this->paysuccessmsg($orderid);
                            $this->result(0,'积分兑换成功','',0,'json');
                        }
                    }
                }
                elseif ($input['pay_type']=='balance'){
                    //余额支付
                    $userinfo=db('user')->where(['acid'=>1,'id'=>$input['uid']])->find();
                    if(floatval($userinfo['money'])>floatval($input['price'])){
                        $res=db('user')->where(['acid'=>1,'id'=>$input['uid']])->setField('money',floatval($userinfo['money'])-floatval($input['price']));
                        if($res){
                            $res2=db('mediaorder')->where(['acid'=>1,'orderid'=>$orderid])->update(['is_pay'=>1,'paytime'=>time()]);
                            if($res2){
                                $this->check_order($orderid);
                                $this->paysuccessmsg($orderid);
                                $this->Yjset($orderid);
                                $this->Jsmoney($orderid);
                                $this->result(0,'余额支付成功','',0,'json');
                            }
                        }
                    }
                }
                elseif ($input['pay_type']=='dypay'){
                    //抖音支付请购买商用版
                }
            }
        }

    }

    //以下为抖音支付签名
    private function httpPost($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) return false;
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    private function sign($map)
    {
        $rList = [];
        foreach ($map as $k => $v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;

            $value = trim(strval($v));
            if (is_array($v)) {
                $value = $this->arrayToStr($v);
            }

            $len = strlen($value);
            if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
                $value = substr($value, 1, $len - 1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            $rList[] = $value;
        }
        $rList[] = "luIID60ZRl4HfCQx8jkiRHAQEC8al8xIsB0TmcBa";
        sort($rList, SORT_STRING);
        return md5(implode('&', $rList));
    }

    private function arrayToStr($map)
    {
        $isMap = $this->isArrMap($map);

        $result = "";
        if ($isMap) {
            $result = "map[";
        }

        $keyArr = array_keys($map);
        if ($isMap) {
            sort($keyArr);
        }

        $paramsArr = array();
        foreach ($keyArr as $k) {
            $v = $map[$k];
            if ($isMap) {
                if (is_array($v)) {
                    $paramsArr[] = sprintf("%s:%s", $k, $this->arrayToStr($v));
                } else {
                    $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
                }
            } else {
                if (is_array($v)) {
                    $paramsArr[] = $this->arrayToStr($v);
                } else {
                    $paramsArr[] = trim(strval($v));
                }
            }
        }

        $result = sprintf("%s%s", $result, join(" ", $paramsArr));
        $result = sprintf("[%s]", $result);

        return $result;
    }

    private function isArrMap($map)
    {
        foreach ($map as $k => $v) {
            if (is_string($k)) {
                return true;
            }
        }

        return false;
    }
}
